import os
from datetime import datetime

from auth import login_required, admin_required, request_limit_check
from config import Config
from extensions import db
from flask import Blueprint, request, session, current_app
from logger_config import get_logger
from models import CostRecord
# 创建查询记录
from models import RequestRecord
from permissions import token_required
from services.agent_service import agent_service
from services.conversation_file_service import ConversationFileService
from services.cost_service import cost_service
from services.query_service import query_service
from services.user_service import user_service
from services.user_stats_service import UserStatsService
from utils.response_utils import create_api_response, generate_execution_summary
from utils.session_utils import get_session_id, clear_session

logger = get_logger(__name__)

# 创建API蓝图
api_bp = Blueprint('api', __name__, url_prefix='/api')


@api_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return create_api_response({
        'status': 'healthy',
        'message': 'API服务正常运行'
    })


@api_bp.route('/initialization/status', methods=['GET'])
def get_initialization_status():
    """获取初始化状态接口（无需认证）"""
    try:
        from config import Config
        config = Config()

        # 检查是否有活跃的会话或配置中的默认会话ID
        active_sessions = agent_service.get_session_count()
        has_default_session = 'DEFAULT_SESSION_ID' in current_app.config
        auto_initialized = active_sessions > 0 or has_default_session

        response_data = {
            'auto_initialized': auto_initialized,
            'active_sessions': active_sessions,
            'auto_init_enabled': os.environ.get('AUTO_INITIALIZE', 'false').lower() == 'true',
            'has_default_session': has_default_session
        }

        # 如果已自动初始化，返回默认配置信息
        if auto_initialized:
            response_data.update({
                'default_model': config.DEFAULT_MODEL,
                'default_data_path': config.DATA_PATH
            })
            
            # 如果没有活跃会话但有默认配置，尝试重新创建agent实例
            if active_sessions == 0 and has_default_session:
                try:
                    default_session_id = current_app.config.get('DEFAULT_SESSION_ID')
                    api_key = current_app.config.get('API_KEY')
                    base_url = current_app.config.get('BASE_URL')
                    model = current_app.config.get('DEFAULT_MODEL')
                    data_path = current_app.config.get('DEFAULT_DATA_PATH')
                    
                    if all([api_key, base_url, model, data_path]):
                        # 重新创建agent实例
                        agent_service.agent_instances[default_session_id] = agent_service._create_agent_direct(
                            api_key, base_url, model, data_path
                        )
                        response_data['active_sessions'] = agent_service.get_session_count()
                        logger.info(f"重新创建agent实例成功，会话ID: {default_session_id}")
                except Exception as e:
                    logger.warning(f"重新创建agent实例失败: {str(e)}")

        response, status_code = create_api_response(response_data)
        return response

    except Exception as e:
        logger.error(f"获取初始化状态失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取初始化状态失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/status', methods=['GET'])
@token_required
def get_system_status():
    """获取系统状态"""
    try:
        # 获取代理服务状态
        active_sessions = agent_service.get_session_count()

        with current_app.app_context():
            # 获取用户统计
            user_stats = user_service.get_user_statistics()

            # 获取系统成本摘要（最近7天）
            cost_summary = cost_service.get_system_cost_summary(days=7)

        status_info = {
            'system': {
                'status': 'running',
                'active_sessions': active_sessions
            },
            'users': user_stats,
            'costs': {
                'recent_cost': cost_summary.get('total_cost', 0),
                'recent_queries': cost_summary.get('total_queries', 0)
            }
        }

        return create_api_response(status_info)

    except Exception as e:
        logger.error(f"获取系统状态失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取系统状态失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/user/profile', methods=['GET'])
@login_required
def get_user_profile():
    """获取用户资料"""
    try:
        from database import get_user_stats
        
        user_id = session.get('user_id')
        with current_app.app_context():
            # 使用database.py中的get_user_stats函数获取完整统计数据
            user_stats_data = get_user_stats(user_id)
            
            if not user_stats_data:
                return create_api_response(
                    None,
                    success=False,
                    message="用户不存在",
                    status_code=404
                )

            # 获取用户成本摘要
            cost_summary = cost_service.get_user_cost_summary(user_id, days=30)
            
            # 获取用户统计摘要（包含正确的token统计）
            user_stats_summary = UserStatsService.get_user_stats_summary(user_id)

        profile_data = {
            'user': user_stats_data['user'],
            'statistics': {
                **user_stats_summary,
                'remaining_weekly_requests': user_stats_data['stats']['remaining_weekly_requests']
            },
            'cost_summary': cost_summary
        }

        return create_api_response(profile_data)

    except Exception as e:
        logger.error(f"获取用户资料失败: {str(e)}")
        return create_api_response(
            None,
            success=False,
            message=f"获取用户资料失败: {str(e)}",
            status_code=500
        )


@api_bp.route('/user/profile', methods=['PUT'])
@login_required
def update_user_profile():
    """更新用户资料"""
    try:
        user_id = session.get('user_id')
        data = request.get_json()

        if not data:
            return create_api_response(
                None,
                success=False,
                message="请提供要更新的数据",
                status_code=400
            )

        # 更新用户资料
        with current_app.app_context():
            result = user_service.update_user_profile(user_id, **data)

        if result['success']:
            return create_api_response(None, message=result['message'])
        else:
            return create_api_response(
                None,
                success=False,
                message=result['error'],
                status_code=400
            )

    except Exception as e:
        logger.error(f"更新用户资料失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"更新用户资料失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/user/change-password', methods=['POST'])
@login_required
def change_password():
    """修改密码"""
    try:
        user_id = session.get('user_id')
        data = request.get_json()

        if not data or 'old_password' not in data or 'new_password' not in data:
            return create_api_response(
                None,
                success=False,
                message="请提供旧密码和新密码",
                status_code=400
            )

        with current_app.app_context():
            result = user_service.change_password(
                user_id,
                data['old_password'],
                data['new_password']
            )

        if result['success']:
            return create_api_response(None, message=result['message'])
        else:
            return create_api_response(
                None,
                success=False,
                message=result['error'],
                status_code=400
            )

    except Exception as e:
        logger.error(f"修改密码失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"修改密码失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/query', methods=['GET'])
@token_required
@request_limit_check
def process_query_get():
    """处理GET方式的查询请求（通过URL参数）- 流式响应"""
    from flask import Response
    import json
    import time
    from utils.conversation_classifier import is_simple_conversation, get_simple_response
    
    try:
        query_text = request.args.get('query', '').strip()
        model = request.args.get('model', '')
        session_id = request.args.get('session_id')  # 获取前端传递的session_id
        
        # 添加调试日志
        logger.info(f"收到查询请求 - query: {query_text[:50]}..., model: {model}, session_id: {session_id}")
        
        if not query_text:
            return create_api_response(
                None,
                success=False,
                message="请提供查询内容",
                status_code=400
            )
        
        # 获取用户ID（从token认证的用户信息中获取）
        from flask import g
        user_id = g.current_user.id if hasattr(g, 'current_user') and g.current_user else 1
        
        # 如果前端没有提供session_id，则生成新的session_id（表示新会话）
        if not session_id:
            import uuid
            session_id = str(uuid.uuid4())
            logger.info(f"前端未提供session_id，生成新的session_id: {session_id}")
        else:
            logger.info(f"使用前端提供的session_id: {session_id}")
        
        # 检查是否为简单对话
        if is_simple_conversation(query_text):
            # 简单对话也通过QueryService处理，确保完整的记录和文件保存
            try:
                # 使用QueryService处理简单对话
                result = query_service.process_query(
                    user_id=user_id,
                    query_text=query_text,
                    session_id=session_id,
                    model=model
                )

                if result.get('success'):
                    simple_reply = result.get('response', get_simple_response(query_text))

                    def generate_simple_response():
                        yield f"data: {json.dumps({'type': 'solution', 'content': simple_reply, 'session_id': session_id}, ensure_ascii=False)}\n\n"
                        yield f"data: {json.dumps({'type': 'complete', 'content': '对话完成'}, ensure_ascii=False)}\n\n"

                    return Response(
                        generate_simple_response(),
                        mimetype='text/plain',
                        headers={
                            'Cache-Control': 'no-cache',
                            'Connection': 'keep-alive',
                            'Access-Control-Allow-Origin': '*'
                        }
                    )
                else:
                    # 如果QueryService处理失败，回退到简单处理
                    simple_reply = get_simple_response(query_text)

                    def generate_simple_response():
                        yield f"data: {json.dumps({'type': 'solution', 'content': simple_reply, 'session_id': session_id}, ensure_ascii=False)}\n\n"
                        yield f"data: {json.dumps({'type': 'complete', 'content': '对话完成'}, ensure_ascii=False)}\n\n"

                    return Response(
                        generate_simple_response(),
                        mimetype='text/plain',
                        headers={
                            'Cache-Control': 'no-cache',
                            'Connection': 'keep-alive',
                            'Access-Control-Allow-Origin': '*'
                        }
                    )
            except Exception as e:
                logger.error(f"简单对话处理失败: {str(e)}")
                # 回退到基本处理
                simple_reply = get_simple_response(query_text)

                def generate_simple_response():
                    yield f"data: {json.dumps({'type': 'solution', 'content': simple_reply, 'session_id': session_id}, ensure_ascii=False)}\n\n"
                    yield f"data: {json.dumps({'type': 'complete', 'content': '对话完成'}, ensure_ascii=False)}\n\n"

                return Response(
                    generate_simple_response(),
                    mimetype='text/plain',
                    headers={
                        'Cache-Control': 'no-cache',
                        'Connection': 'keep-alive',
                        'Access-Control-Allow-Origin': '*'
                    }
                )

        # 检查是否有活跃的代理实例
        active_sessions = agent_service.get_session_count()
        if active_sessions == 0:
            return create_api_response(
                None,
                success=False,
                message="代理未初始化，请先初始化代理",
                status_code=400
            )
        
        # 如果没有提供session_id，则获取第一个可用的会话ID
        if not session_id:
            session_ids = agent_service.get_all_sessions()
            if not session_ids:
                return create_api_response(
                    None,
                    success=False,
                    message="没有可用的代理会话",
                    status_code=400
                )
            session_id = session_ids[0]  # 使用第一个可用会话
            logger.info(f"复杂任务使用现有代理会话: {session_id}")
        else:
            # 检查提供的session_id是否存在对应的代理实例
            if not agent_service.get_agent_instance(session_id):
                # 如果提供的session_id没有对应的代理实例，为该session_id创建新的代理实例
                try:
                    # 获取任意一个现有代理实例作为模板
                    session_ids = agent_service.get_all_sessions()
                    if session_ids:
                        template_agent = agent_service.get_agent_instance(session_ids[0])

                        if template_agent:
                            # 使用模板代理的配置为新session_id创建代理实例
                            # 从环境变量获取API配置信息
                            api_key = os.environ.get('ANTHROPIC_API_KEY') or os.environ.get('OPENAI_API_KEY', 'default_key')
                            base_url = os.environ.get('ANTHROPIC_BASE_URL') or os.environ.get('OPENAI_BASE_URL', 'default_url')
                            
                            # 使用Config中的DATA_PATH确保路径一致性
                            from config import Config
                            config = Config()
                            
                            # 获取正确的模型名称
                            model_name = config.DEFAULT_MODEL  # 使用配置中的默认模型
                            if hasattr(template_agent, 'llm') and template_agent.llm:
                                if hasattr(template_agent.llm, 'model_name'):
                                    model_name = template_agent.llm.model_name
                                elif hasattr(template_agent.llm, 'model'):
                                    model_name = template_agent.llm.model
                            
                            new_agent = agent_service._create_agent_direct(
                                api_key=api_key,
                                base_url=base_url,
                                llm_model=model_name,
                                data_path=config.DATA_PATH
                            )
                            # 手动将新代理实例添加到指定的session_id
                            agent_service.agent_instances[session_id] = new_agent
                            logger.info(f"为session_id {session_id} 创建了新的代理实例")
                        else:
                            return create_api_response(
                                None,
                                success=False,
                                message="无法获取代理模板配置",
                                status_code=500
                            )
                    else:
                        return create_api_response(
                            None,
                            success=False,
                            message="没有可用的代理会话",
                            status_code=400
                        )
                except Exception as e:
                    logger.error(f"创建代理实例时出错: {str(e)}")
                    return create_api_response(
                        None,
                        success=False,
                        message=f"创建代理实例失败: {str(e)}",
                        status_code=500
                    )
        
        # 获取当前应用实例
        app = current_app._get_current_object()

        # 存储执行结果的容器
        execution_result = {
            'agent_output': None,
            'log_data': [],
            'execution_time': 0,
            'cost_info': {},
            'error': None,
            'request_record': None,
            'user_id': user_id,
            'query_text': query_text,
            'session_id': session_id
        }
        
        def generate_stream():
            """生成流式响应"""
            with app.app_context():
                try:
                    # 在函数内部导入Config以避免作用域问题
                    from config import Config
                    
                    # 发送开始消息
                    yield f"data: {json.dumps({'type': 'agent_start', 'content': '开始处理查询...'}, ensure_ascii=False)}\n\n"
                    
                    # 获取代理实例
                    agent = agent_service.get_agent_instance(session_id)
                    if not agent:
                        yield f"data: {json.dumps({'type': 'error', 'content': '代理实例不存在'}, ensure_ascii=False)}\n\n"
                        return

                    # 获取用户ID（从执行结果容器中获取，避免访问session）
                    user_id = execution_result['user_id']
                    
                    # 准备会话工作目录
                    session_work_dir = query_service._prepare_session_work_directory(user_id, session_id)

                    # 创建请求记录
                    request_record = RequestRecord(
                        user_id=user_id,
                        session_id=session_id,
                        query=query_text,
                        model=Config.DEFAULT_MODEL,
                        status='processing',
                        started_at=datetime.utcnow()
                    )
                    db.session.add(request_record)
                    db.session.commit()

                    # 保存请求记录到结果容器
                    execution_result['request_record'] = request_record
                    
                    start_time = time.time()
                    
                    # 执行代理查询
                    yield f"data: {json.dumps({'type': 'task_start', 'content': f'执行查询 (ID: {request_record.id})'}, ensure_ascii=False)}\n\n"
                    
                    # 使用流式执行获取实时输出
                    agent_output = None
                    log_data = []
                    all_outputs = []  # 收集所有输出
                    intermediate_steps = []  # 收集中间步骤用于保存

                    # 初始化对话文件服务
                    conversation_service = ConversationFileService()
                    
                    # 获取流式输出，添加错误处理
                    try:
                        # 检查agent是否有go_stream方法
                        if not hasattr(agent, 'go_stream'):
                            logger.warning("代理对象没有go_stream方法，使用非流式方法")
                            raise AttributeError("Agent does not have go_stream method")
                        
                        stream_result = agent.go_stream(query_text, session_work_dir=session_work_dir)
                        if stream_result is None:
                            logger.warning("agent.go_stream返回None，尝试使用非流式方法")
                            raise ValueError("Stream result is None")
                        
                        # 检查stream_result是否可迭代
                        try:
                            iter(stream_result)
                        except TypeError:
                            logger.warning("流式输出结果不可迭代，尝试使用非流式方法")
                            raise TypeError("Stream result is not iterable")

                        step_index = 0
                        for step in stream_result:
                            if step is None:
                                logger.warning("流式输出中遇到None步骤，跳过")
                                continue
                            
                            step_output = step.get('output', '') if isinstance(step, dict) else ''
                            if step_output:
                                # 发送实时步骤输出
                                yield f"data: {json.dumps({'type': 'reasoning', 'content': str(step_output)}, ensure_ascii=False)}\n\n"
                                all_outputs.append(str(step_output))  # 收集所有输出
                                log_data.append(step)  # 收集日志数据

                                # 准备中间步骤数据
                                step_data = {
                                    'step_type': 'reasoning',
                                    'content': str(step_output),
                                    'formatted_output': str(step_output),
                                    'raw_data': step if isinstance(step, dict) else {'output': step_output},
                                    'tool_calls': step.get('tool_calls', []) if isinstance(step, dict) else [],
                                    'metadata': {
                                        'step_index': step_index,
                                        'timestamp': datetime.now().isoformat(),
                                        'is_streaming': True
                                    }
                                }
                                intermediate_steps.append(step_data)

                                # 实时保存中间步骤到executions文件
                                try:
                                    conversation_service.save_intermediate_step(
                                        session_id=session_id,
                                        query_id=str(request_record.id),
                                        step_data=step_data,
                                        step_index=step_index
                                    )
                                except Exception as save_error:
                                    logger.warning(f"保存中间步骤失败: {save_error}")

                                step_index += 1
                    except (TypeError, ValueError, AttributeError, Exception) as stream_error:
                        logger.warning(f"流式输出失败: {stream_error}，尝试使用非流式方法")
                        # 流式输出失败时的fallback处理将在下面执行
                    
                    # 如果有输出，合并所有输出作为最终结果
                    if all_outputs:
                        agent_output = '\n'.join(all_outputs)
                    else:
                        # 如果流式输出为空，尝试直接调用代理获取结果
                        try:
                            agent_output = agent.go(query_text)
                        except Exception as fallback_error:
                            logger.warning(f"非流式方法也失败: {fallback_error}")
                            agent_output = "抱歉，当前服务繁忙，请稍后重试。"
                    
                    # 获取完整的日志和最终结果
                    if hasattr(agent, 'log'):
                        log_data.extend(agent.log)
                    
                    # 发送最终结果
                    if agent_output:
                        yield f"data: {json.dumps({'type': 'message', 'content': str(agent_output)}, ensure_ascii=False)}\n\n"
                    
                    # 计算执行时间和成本
                    execution_time = time.time() - start_time
                    # 先生成初步的执行摘要（不包含token信息）
                    execution_summary = generate_execution_summary(
                        log_data, agent_output, query_text, execution_time, 0, 0
                    ) if log_data else {}
                    # 然后计算成本信息
                    cost_info = cost_service.calculate_query_cost(
                        query_text, agent_output, execution_summary, model
                    )
                    # 重新生成包含token信息的执行摘要
                    if log_data:
                        execution_summary = generate_execution_summary(
                            log_data, agent_output, query_text, execution_time,
                            cost_info.get('input_tokens', 0), cost_info.get('output_tokens', 0)
                        )

                    # 立即更新请求记录和创建成本记录（在主线程中）
                    try:
                        logger.info(f"开始更新请求记录 {request_record.id}，成本信息: {cost_info}")
                        
                        request_record.response = str(agent_output) if agent_output else None
                        request_record.duration = execution_time
                        request_record.input_tokens = cost_info.get('input_tokens', 0)
                        request_record.output_tokens = cost_info.get('output_tokens', 0)
                        request_record.status = 'completed'
                        request_record.completed_at = datetime.utcnow()

                        # 检查是否已存在成本记录，避免重复插入
                        existing_cost_record = CostRecord.query.filter_by(request_id=request_record.id).first()
                        logger.info(f"检查现有成本记录，request_id={request_record.id}，existing_cost_record={existing_cost_record}")
                        
                        if not existing_cost_record:
                            # 创建成本记录
                            logger.info(f"创建新的成本记录，参数: user_id={user_id}, request_id={request_record.id}, model={request_record.model}")
                            cost_record = CostRecord(
                                user_id=user_id,
                                request_id=request_record.id,
                                model=request_record.model,
                                input_tokens=cost_info.get('input_tokens', 0),
                                output_tokens=cost_info.get('output_tokens', 0),
                                input_cost=cost_info.get('input_cost', 0.0),
                                output_cost=cost_info.get('output_cost', 0.0),
                                cost=cost_info.get('total_cost', 0.0)
                            )
                            db.session.add(cost_record)
                            logger.info(f"成本记录已添加到会话，ID: {cost_record.id}, 成本: ${cost_info.get('total_cost', 0.0)}")
                        else:
                            logger.info(f"请求 {request_record.id} 的成本记录已存在，跳过创建")
                        
                        # 统一提交RequestRecord更新和CostRecord创建
                        logger.info(f"准备提交数据库事务，request_id={request_record.id}")
                        db.session.commit()
                        logger.info(f"数据库事务提交成功，request_id={request_record.id}")

                        # 更新用户统计
                        UserStatsService.update_query_stats(
                            user_id=user_id,
                            model=Config.DEFAULT_MODEL,
                            status='completed',
                            input_tokens=cost_info.get('input_tokens', 0),
                            output_tokens=cost_info.get('output_tokens', 0),
                            total_cost=cost_info.get('total_cost', 0.0),
                            duration=execution_time
                        )
                        
                    except Exception as db_error:
                        logger.error(f"数据库操作失败: {str(db_error)}")
                        # 数据库操作失败不影响响应流程

                    # 保存执行结果供后续处理
                    execution_result.update({
                        'agent_output': agent_output,
                        'log_data': log_data,
                        'all_outputs': all_outputs,
                        'intermediate_steps': intermediate_steps,
                        'execution_time': execution_time,
                        'cost_info': cost_info,
                        'final_response': agent_output  # 添加final_response字段
                    })
                    
                    # 生成智能总结
                    try:
                        yield f"data: {json.dumps({'type': 'task_start', 'content': '正在生成智能总结...'}, ensure_ascii=False)}\n\n"
                        
                        # 调用智能总结服务
                        intelligent_summary = generate_execution_summary(
                            log=log_data,
                            result=agent_output,
                            query=query_text,
                            execution_time=execution_time
                        )
                        
                        if intelligent_summary:
                            yield f"data: {json.dumps({'type': 'intelligent_summary', 'content': intelligent_summary}, ensure_ascii=False)}\n\n"
                        
                    except Exception as summary_error:
                        logger.warning(f"生成智能总结失败: {summary_error}")
                        # 总结失败不影响主流程
                    
                    # 发送完成消息
                    yield f"data: {json.dumps({'type': 'complete', 'content': '查询处理完成'}, ensure_ascii=False)}\n\n"
                    
                except Exception as e:
                    execution_result['error'] = str(e)
                    logger.error(f"流式查询处理失败: {str(e)}")
                    # 不中断流程，提供友好的错误提示
                    yield f"data: {json.dumps({'type': 'error', 'content': '服务暂时不可用，请稍后重试'}, ensure_ascii=False)}\n\n"

        def post_process_callback():
            """流式响应完成后的回调处理 - 主要处理对话文件保存"""
            try:
                if execution_result['error']:
                    return  # 如果有错误，不进行后续处理

                request_record = execution_result['request_record']
                if not request_record:
                    return

                # 获取用户ID（从执行结果中获取）
                user_id = execution_result.get('user_id', 1)
                agent_output = execution_result['agent_output']

                # 创建对话文件记录
                try:
                    conversation_service = ConversationFileService()
                    conversation_file = conversation_service.create_conversation_record(
                        user_id=user_id,
                        request_id=request_record.id,
                        query_text=execution_result['query_text'],
                        response_text=str(agent_output) if agent_output else None,
                        log_data=execution_result['log_data'],
                        session_id=execution_result['session_id']
                    )
                    logger.info(f"对话文件已保存到: {conversation_file.timestamp_folder}")

                    # 保存完整的执行过程数据
                    try:
                        execution_data = {
                            'query_text': execution_result['query_text'],
                            'final_response': execution_result.get('final_response', ''),
                            'log_data': execution_result['log_data'],
                            'all_outputs': execution_result.get('all_outputs', []),
                            'intermediate_steps': execution_result.get('intermediate_steps', []),
                            'execution_time': execution_result.get('execution_time', 0),
                            'total_cost': execution_result.get('cost_info', {}).get('total_cost', 0.0),
                            'timestamp': datetime.now().isoformat()
                        }
                        execution_file_path = conversation_service.save_execution_process(
                            session_id=execution_result['session_id'],
                            query_id=str(request_record.id),
                            execution_data=execution_data
                        )
                        logger.info(f"执行过程数据已保存到: {execution_file_path}")
                    except Exception as exec_error:
                        logger.error(f"保存执行过程数据失败: {str(exec_error)}")
                        
                except Exception as file_error:
                    logger.error(f"保存对话文件失败: {str(file_error)}")

            except Exception as e:
                logger.error(f"后处理回调失败: {str(e)}")

        # 创建响应对象
        response = Response(
            generate_stream(),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Cache-Control'
            }
        )

        # 使用线程在响应发送后执行后处理
        import threading

        def delayed_callback():
            import time
            time.sleep(1)  # 等待响应发送完成
            try:
                with app.app_context():
                    post_process_callback()
            except Exception as e:
                logger.error(f"后处理回调执行失败: {str(e)}")
                # 如果回调失败，至少更新状态为completed
                try:
                    with app.app_context():
                        request_record = execution_result.get('request_record')
                        if request_record:
                            request_record.status = 'completed'
                            request_record.completed_at = datetime.utcnow()
                            db.session.commit()
                            logger.info(f"请求记录 {request_record.id} 状态已更新为completed")
                except Exception as fallback_error:
                    logger.error(f"状态更新回退也失败: {str(fallback_error)}")

        thread = threading.Thread(target=delayed_callback)
        thread.daemon = True
        thread.start()

        return response
    
    except Exception as e:
        logger.error(f"查询处理失败: {str(e)}")
        response, status_code = create_api_response(
            None,
            success=False,
            message=f"查询处理失败: {str(e)}",
            status_code=500
        )
        return response, status_code


@api_bp.route('/queries', methods=['GET'])
@login_required
def get_query_history():
    """获取查询历史"""
    try:
        user_id = session.get('user_id')
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)

        # 限制每页数量
        per_page = min(per_page, 100)

        offset = (page - 1) * per_page
        with current_app.app_context():
            queries = query_service.get_query_history(user_id, per_page, offset)

        return create_api_response({
            'queries': queries,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': len(queries)
            }
        })

    except Exception as e:
        logger.error(f"获取查询历史失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取查询历史失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/queries/<int:query_id>', methods=['GET'])
@login_required
def get_query_detail(query_id):
    """获取查询详情"""
    try:
        user_id = session.get('user_id')
        with current_app.app_context():
            query = query_service.get_query_by_id(query_id, user_id)

        if not query:
            return create_api_response(
                None,
                success=False,
                message="查询记录不存在或无权访问",
                status_code=404
            )

        return create_api_response(query)

    except Exception as e:
        logger.error(f"获取查询详情失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取查询详情失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/queries/<int:query_id>', methods=['DELETE'])
@login_required
def delete_query(query_id):
    """删除查询记录"""
    try:
        user_id = session.get('user_id')
        with current_app.app_context():
            success = query_service.delete_query(query_id, user_id)

        if success:
            return create_api_response(None, message="查询记录删除成功")
        else:
            return create_api_response(
                None,
                success=False,
                message="查询记录不存在或删除失败",
                status_code=404
            )

    except Exception as e:
        logger.error(f"删除查询记录失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"删除查询记录失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/session/clear', methods=['POST'])
@login_required
def clear_user_session():
    """清除用户会话"""
    try:
        session_id = get_session_id()

        # 移除代理实例
        if session_id:
            agent_service.remove_agent_instance(session_id)

        # 清除会话数据
        clear_session()

        return create_api_response(None, message="会话清除成功")

    except Exception as e:
        logger.error(f"清除会话失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"清除会话失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/models', methods=['GET'])
@token_required
def get_supported_models():
    """获取支持的模型列表"""
    try:
        from config import Config
        config = Config()

        models = [{
            'name': model,
            'platform': platform
        } for model, platform in config.MODEL_PLATFORM_MAP.items()]

        return create_api_response({
            'models': models,
            'default_model': config.DEFAULT_MODEL
        })

    except Exception as e:
        logger.error(f"获取模型列表失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取模型列表失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/pricing', methods=['GET'])
@admin_required
def get_model_pricing():
    """获取模型定价信息（管理员）"""
    try:
        with current_app.app_context():
            pricing_info = cost_service.get_all_model_pricing()
        return create_api_response(pricing_info)

    except Exception as e:
        logger.error(f"获取模型定价失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取模型定价失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/pricing/<model_name>', methods=['PUT'])
@admin_required
def update_model_pricing(model_name):
    """更新模型定价（管理员）"""
    try:
        data = request.get_json()

        if not data or 'input_price' not in data or 'output_price' not in data:
            return create_api_response(
                None,
                success=False,
                message="请提供输入和输出价格",
                status_code=400
            )

        with current_app.app_context():
            result = cost_service.update_model_pricing(
                model_name,
                data['input_price'],
                data['output_price']
            )

        if result['success']:
            return create_api_response(None, message=result['message'])
        else:
            return create_api_response(
                None,
                success=False,
                message=result['error'],
                status_code=400
            )

    except Exception as e:
        logger.error(f"更新模型定价失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"更新模型定价失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/admin/users', methods=['GET'])
@admin_required
def get_all_users():
    """获取所有用户（管理员）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)

        # 限制每页数量
        per_page = min(per_page, 100)

        with current_app.app_context():
            result = user_service.get_all_users(page, per_page)
        return create_api_response(result)

    except Exception as e:
        logger.error(f"获取用户列表失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取用户列表失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/admin/users/<int:user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    """删除用户（管理员）"""
    try:
        with current_app.app_context():
            result = user_service.delete_user(user_id)

        if result['success']:
            return create_api_response(None, message=result['message'])
        else:
            return create_api_response(
                None,
                success=False,
                message=result['error'],
                status_code=400
            )

    except Exception as e:
        logger.error(f"删除用户失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"删除用户失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/admin/system/cost-summary', methods=['GET'])
@admin_required
def get_system_cost_summary():
    """获取系统成本摘要（管理员）"""
    try:
        days = request.args.get('days', 30, type=int)
        days = min(days, 365)  # 限制最大天数

        with current_app.app_context():
            cost_summary = cost_service.get_system_cost_summary(days)
        return create_api_response(cost_summary)

    except Exception as e:
        logger.error(f"获取系统成本摘要失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取系统成本摘要失败: {str(e)}"
        )

        response.status_code = 500

        return response


# 用户统计相关API
@api_bp.route('/user/stats', methods=['GET'])
@login_required
def get_user_stats():
    """获取用户统计信息"""
    try:
        user_id = session.get('user_id')
        stats = UserStatsService.get_user_stats_summary(user_id)
        return create_api_response({
            'stats': stats
        })
    except Exception as e:
        logger.error(f"获取用户统计失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取用户统计失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/user/stats/daily', methods=['GET'])
@login_required
def get_user_daily_stats():
    """获取用户每日统计"""
    try:
        user_id = session.get('user_id')
        days = request.args.get('days', 30, type=int)
        days = min(days, 90)  # 限制最多90天

        daily_stats = UserStatsService.get_user_daily_stats(user_id, days)
        return create_api_response({
            'daily_stats': daily_stats,
            'days': days
        })
    except Exception as e:
        logger.error(f"获取用户每日统计失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取用户每日统计失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/user/stats/models', methods=['GET'])
@login_required
def get_user_model_stats():
    """获取用户模型使用统计"""
    try:
        user_id = session.get('user_id')
        model_stats = UserStatsService.get_user_model_stats(user_id)
        return create_api_response({
            'model_stats': model_stats
        })
    except Exception as e:
        logger.error(f"获取用户模型统计失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取用户模型统计失败: {str(e)}"
        )

        response.status_code = 500

        return response


# 对话文件管理相关API
@api_bp.route('/conversations', methods=['GET'])
@login_required
def get_conversations():
    """获取用户对话列表"""
    try:
        user_id = session.get('user_id')
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        per_page = min(per_page, 100)  # 限制每页数量

        offset = (page - 1) * per_page
        conversation_service = ConversationFileService()
        conversations = conversation_service.get_user_conversations(user_id, per_page, offset)

        # 转换为可序列化格式
        conversation_list = []
        for conv in conversations:
            conv_data = {
                'id': conv.id,
                'timestamp_folder': conv.timestamp_folder,
                'title': conv.title,
                'session_id': conv.session_id,
                'message_count': conv.message_count,
                'total_tokens': conv.total_tokens,
                'total_cost': conv.total_cost,
                'total_size': conv.total_size,
                'created_at': conv.created_at.isoformat(),
                'updated_at': conv.updated_at.isoformat(),
                'last_message_at': conv.last_message_at.isoformat() if conv.last_message_at else None
            }
            
            # 检查是否有执行记录文件
            has_execution_data = False
            execution_count = 0
            if conv.execution_files and isinstance(conv.execution_files, list):
                has_execution_data = True
                execution_count = len(conv.execution_files)
            
            conv_data['has_execution_data'] = has_execution_data
            conv_data['execution_count'] = execution_count
            
            # 添加查询摘要信息（用于前端显示）
            if conv.title:
                conv_data['query_summary'] = conv.title
            else:
                # 如果没有标题，尝试从第一个查询中获取摘要
                conv_data['query_summary'] = f"会话 {conv.session_id[:8]}..."
            
            conversation_list.append(conv_data)

        return create_api_response({
            'conversations': conversation_list,
            'page': page,
            'per_page': per_page
        })
    except Exception as e:
        logger.error(f"获取对话列表失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取对话列表失败: {str(e)}"
        )
        response.status_code = 500
        return response


@api_bp.route('/conversations/<int:conversation_id>', methods=['GET'])
@login_required
def get_conversation_detail(conversation_id):
    """获取对话详情"""
    try:
        user_id = session.get('user_id')
        conversation_service = ConversationFileService()
        conversation = conversation_service.get_conversation_by_id(conversation_id, user_id)

        if not conversation:
            return create_api_response(
                None,
                success=False,
                message="对话记录不存在",
                status_code=404
            )

        # 构建返回数据
        conversation_data = {
            'id': conversation.id,
            'user_id': conversation.user_id,
            'session_id': conversation.session_id,
            'title': conversation.title,
            'timestamp_folder': conversation.timestamp_folder,
            'conversation_dir': conversation.conversation_dir,
            'message_count': conversation.message_count,
            'total_tokens': conversation.total_tokens,
            'total_cost': conversation.total_cost,
            'total_size': conversation.total_size,
            'created_at': conversation.created_at.isoformat(),
            'updated_at': conversation.updated_at.isoformat(),
            'last_message_at': conversation.last_message_at.isoformat() if conversation.last_message_at else None
        }
        
        # 添加执行记录信息
        if conversation.execution_files and isinstance(conversation.execution_files, list):
            conversation_data['execution_files'] = conversation.execution_files
            conversation_data['has_execution_data'] = True
            conversation_data['execution_count'] = len(conversation.execution_files)
        else:
            conversation_data['execution_files'] = []
            conversation_data['has_execution_data'] = False
            conversation_data['execution_count'] = 0

        return create_api_response({
            'conversation': conversation_data
        })
    except Exception as e:
        logger.error(f"获取对话详情失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取对话详情失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/conversations/<int:conversation_id>/content', methods=['GET'])
@login_required
def get_conversation_content(conversation_id):
    """获取对话完整内容"""
    try:
        user_id = session.get('user_id')
        conversation_service = ConversationFileService()
        content = conversation_service.get_conversation_content(conversation_id, user_id)

        if not content:
            return create_api_response(
                None,
                success=False,
                message="对话记录不存在",
                status_code=404
            )

        # 获取会话记录以检查执行记录信息
        conversation = conversation_service.get_conversation_by_id(conversation_id, user_id)
        if conversation:
            # 添加执行记录信息到内容中
            content['has_execution_data'] = bool(conversation.execution_files and len(conversation.execution_files) > 0)
            content['execution_count'] = len(conversation.execution_files) if conversation.execution_files else 0
            content['execution_files'] = conversation.execution_files if conversation.execution_files else []

        return create_api_response({
            'conversation_content': content
        })
    except Exception as e:
        logger.error(f"获取对话内容失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取对话内容失败: {str(e)}"
        )
        response.status_code = 500
        return response


@api_bp.route('/conversations/<int:conversation_id>/execution/<query_id>', methods=['GET'])
@login_required
def get_execution_process(conversation_id, query_id):
    """获取执行记录详细信息"""
    try:
        # 获取会话记录
        conversation_service = ConversationFileService()
        conversation = conversation_service.get_conversation_by_id(conversation_id, session.get('user_id'))
        if not conversation:
            return create_api_response(
                {'error': '会话不存在'},
                status_code=404
            )
        
        # 获取执行记录详细信息
        execution_data = conversation_service.get_execution_process(
            conversation.session_id, query_id
        )
        
        if not execution_data:
            return create_api_response(
                {'error': '执行记录不存在'},
                status_code=404
            )
        
        return create_api_response({
            'execution_data': execution_data
        })
        
    except Exception as e:
        logger.error(f"获取执行记录失败: {str(e)}")
        return create_api_response(
            {'error': '获取执行记录失败'},
            status_code=500
        )


@api_bp.route('/conversations/<int:conversation_id>', methods=['DELETE'])
@login_required
def delete_conversation(conversation_id):
    """删除对话记录"""
    try:
        user_id = session.get('user_id')
        conversation_service = ConversationFileService()

        if conversation_service.delete_conversation(conversation_id, user_id):
            return create_api_response({
                'message': '对话记录删除成功'
            })
        else:
            return create_api_response(
                None,
                success=False,
                message="对话记录不存在或删除失败",
                status_code=404
            )
    except Exception as e:
        logger.error(f"删除对话记录失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"删除对话记录失败: {str(e)}"
        )
        response.status_code = 500
        return response


@api_bp.route('/conversations/download', methods=['POST'])
@login_required
def download_conversations():
    """下载对话记录"""
    try:
        user_id = session.get('user_id')
        data = request.get_json() or {}
        conversation_ids = data.get('conversation_ids')  # 可选，如果不提供则下载所有

        conversation_service = ConversationFileService()
        

        
        zip_path = conversation_service.create_download_archive(user_id, conversation_ids)

        if not zip_path:
            return create_api_response(
                None,
                success=False,
                message="没有找到可下载的对话记录",
                status_code=404
            )

        # 返回下载链接或文件路径
        import os
        filename = os.path.basename(zip_path)

        return create_api_response({
            'download_url': f'/api/conversations/download/{filename}',
            'filename': filename,
            'message': '对话记录打包完成，请点击下载'
        })
    except Exception as e:
        logger.error(f"下载对话记录失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"下载对话记录失败: {str(e)}"
        )
        response.status_code = 500
        return response


@api_bp.route('/conversations/storage-stats', methods=['GET'])
@login_required
def get_storage_stats():
    """获取存储统计信息"""
    try:
        user_id = session.get('user_id')
        conversation_service = ConversationFileService()
        stats = conversation_service.get_storage_stats(user_id)

        return create_api_response({
            'storage_stats': stats
        })
    except Exception as e:
        logger.error(f"获取存储统计失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取存储统计失败: {str(e)}"
        )

        response.status_code = 500

        return response


@api_bp.route('/conversations/download/<filename>', methods=['GET'])
@login_required
def download_conversation_file(filename):
    """下载对话记录文件"""
    try:
        from flask import send_file
        from services.conversation_file_service import ConversationFileService
        
        user_id = session.get('user_id')
        conversation_service = ConversationFileService()
        
        # 构建文件路径（用户downloads目录）
        user_dir = conversation_service.get_user_directory(user_id)
        downloads_dir = os.path.join(user_dir, 'downloads')
        file_path = os.path.join(downloads_dir, filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            return create_api_response(
                None,
                success=False,
                message="文件不存在或已过期",
                status_code=404
            )
        
        # 发送文件
        return send_file(
            file_path,
            as_attachment=True,
            download_name=filename,
            mimetype='application/zip'
        )
        
    except Exception as e:
        logger.error(f"下载文件失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"下载文件失败: {str(e)}"
        )

        response.status_code = 500

        return response


# 管理员统计API
@api_bp.route('/admin/stats/system', methods=['GET'])
@admin_required
def get_system_stats():
    """获取系统整体统计（管理员）"""
    try:
        stats = UserStatsService.get_system_stats()
        return create_api_response({
            'system_stats': stats
        })
    except Exception as e:
        logger.error(f"获取系统统计失败: {str(e)}")
        response = create_api_response(
            None,
            success=False,
            message=f"获取系统统计失败: {str(e)}"
        )

        response.status_code = 500

        return response


# 错误处理
@api_bp.errorhandler(400)
def bad_request(error):
    return create_api_response(
        None,
        success=False,
        message="请求参数错误",
        status_code=400
    )


@api_bp.errorhandler(401)
def unauthorized(error):
    return create_api_response(
        None,
        success=False,
        message="未授权访问",
        status_code=401
    )


@api_bp.errorhandler(403)
def forbidden(error):
    return create_api_response(
        None,
        success=False,
        message="权限不足",
        status_code=403
    )


@api_bp.errorhandler(404)
def not_found(error):
    return create_api_response(
        None,
        success=False,
        message="资源不存在",
        status_code=404
    )


@api_bp.errorhandler(500)
def internal_error(error):
    return create_api_response(
        None,
        success=False,
        message="服务器内部错误",
        status_code=500
    )
